package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 用户新增地址
     * @param addressBook
     */
    @Override
    public void add(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 用户修改地址
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 用户删除地址
     * @param id
     */
    @Override
    public void delete(Long id) {
        addressBookMapper.delete(id);
    }

    /**
     * 列出用户地址
     * @return
     */
    @Override
    public List<AddressBook> list() {
        AddressBook addressBook=new AddressBook();
        addressBook.setUserId(BaseContext.getCurrentId());
        return addressBookMapper.list(addressBook);
    }

    /**
     * 设置默认地址
     * @param id
     */
    @Override
    @Transactional
    public void setDefault(Long id) {
        //清空默认状态
        addressBookMapper.clearDefault(BaseContext.getCurrentId());
        //设置默认状态
        AddressBook addressBook=AddressBook.builder()
                        .id(id)
                        .isDefault(StatusConstant.ENABLE)
                        .build();
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id获取地址
     * @param id
     * @return
     */
    @Override
    public AddressBook getAddressBookById(Long id) {
        return addressBookMapper.getAddressBookById(id);
    }

    /**
     * 查询默认地址
     * @return
     */
    @Override
    public AddressBook getDefault() {
        AddressBook addressBook=AddressBook.builder()
                .isDefault(StatusConstant.ENABLE)
                .userId(BaseContext.getCurrentId())
                .build();
        List<AddressBook> list=addressBookMapper.list(addressBook);
        if(list==null||list.isEmpty()){
            return null;
        }
        return list.get(0);
    }


}
